﻿Imports System.Collections.Generic
Imports AutoMapper
Imports VMWorkshop.Domain

Public Class AjaxViewModel
    Private _products As IList(Of ProductListView) = Nothing
    Private _repository As IProductRepository = Nothing
    Private _isPersistActionComplete As Boolean = False

    Public ReadOnly Property IsPersistActionComplete() As Boolean
        Get
            Return Me._isPersistActionComplete
        End Get
    End Property

    Public ReadOnly Property Products() As IList(Of ProductListView)
        Get
            If Me._products Is Nothing Then
                Dim p As IList(Of Product) = Me._repository.GetAll()
                Me._products = Mapper.Map(Of IList(Of Product), IList(Of ProductListView))(p)
            End If
            Return Me._products
        End Get
    End Property

    Public Sub New(ByVal repository As IProductRepository)
        Me._repository = repository
    End Sub

    Friend Function GetProductById(ByVal productId As Integer) As ProductEditView
        Dim product As Product = Me._repository.GetProductById(productId)
        Return ProductEditView.ToProductEditView(product)
    End Function

    Friend Sub PersistChanges(ByVal editView As ProductEditView)
        Dim newProduct As Product = ProductEditView.ToProduct(editView)
        Dim oldProduct As Product = Me._repository.GetProductById(newProduct.ProductId)

        With oldProduct
            .Title = newProduct.Title
            .Description = newProduct.Description
            .QuantityOnHand = newProduct.QuantityOnHand
            .ReleaseDate = newProduct.ReleaseDate
            .Price = newProduct.Price
        End With

        Me._repository.Persist(oldProduct)
        Me._isPersistActionComplete = True
    End Sub
End Class